﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using DataScripter.Excel.FormattedValues;
using DataScripter.Excel.Formatters;

namespace DataScripter.Excel.Table
{
	internal class TableRow
	{
		private readonly IDictionary<TableColumn, object> _values;

		public TableRow(int rowNumber, IEnumerable<TableColumn> columns) : this(rowNumber, new NoFormatter(), columns)
		{}

		public TableRow(int rowNumber, ICellFormatter formatter, IEnumerable<TableColumn> columns)
		{
			RowNumber = rowNumber;
			Formatter = formatter;

			Debug.Assert(columns != null, "columns != null");
			Columns = columns.ToArray();
			_values = columns.ToDictionary(c => c, c => (object)null);
		}

		public int RowNumber { get; set; }
		public ICellFormatter Formatter { get; set; }
		public TableColumn[] Columns { get; set; }

		public object[] Values
		{
			get { return _values
				.Select(kvp => new GenericFormattedValue<object>(kvp.Value,kvp.Key.Formatter))
				.ToArray(); }
		}

		public object this[string columnName]
		{
			get { return _values[Column(columnName)]; }
			set { _values[Column(columnName)] = value; }
		}

		private TableColumn Column(string columName)
		{
			return Columns.Single(c=> c.ColumnName == columName);
		}

		public void Set(string columnName, object value)
		{
			_values[Column(columnName)] = value;
		}

		public void Set(object[] cells)
		{
			for (int i = 0; i < Columns.Length; i++)
			{
				_values[Columns[i]] = cells[i];
			}
		}
	}
}